﻿// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using IdentityServer4;
using IdentityServer4.ResponseHandling;

using IdentityServerHost.Quickstart.UI;

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using MyIdentity.InterfaceImplementation;

using MyIdentity;
using MyIdentity.Register;

using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace MyIdentity
{
    public class Startup
    {
        public IWebHostEnvironment Environment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }
    



        public void ConfigureServices(IServiceCollection services)
        {

  
            services.AddControllersWithViews();

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;
                //  options.Discovery.CustomEntries.Add("");
           
                // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                options.EmitStaticAudienceClaim = true;
            })
                .AddTestUsers(TestUsers.Users);


            // in-memory, code config
            builder.AddInMemoryIdentityResources(Config.IdentityResources);
            builder.AddInMemoryApiScopes(Config.ApiScopes);
            builder.AddInMemoryClients(Config.Clients);
            builder.AddInMemoryApiResources(Config.ApiResources);

            // not recommended for production - you need to store your key material somewhere secure
            // builder.AddDeveloperSigningCredential();
            // builder.Services.AddScoped<IDiscoveryResponseGenerator,MyDiscoveryResponseGenerator>();
           
             builder.AddSigningCredential(new X509Certificate2("/etc/ssl/www.liujian520.asia.pfx", "02iws9ro"));
             services.AddAuthentication()
                .AddGoogle(options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                    
                    // register your IdentityServer with Google at https://console.developers.google.com
                    // enable the Google+ API
                    // set the redirect URI to https://localhost:5001/signin-google
                    options.ClientId = "copy client ID from Google here";
                    options.ClientSecret = "copy client secret from Google here";
                });

            //  services.ConfigureNonBreakingSameSiteCookies();
            services.Configure<ConsulRegisterOptions>(Configuration.GetSection("ConsulSetting"));

            services.AddConsulRegister();
            services.AddSameSiteCookiePolicy();
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
            //    options.Secure = CookieSecurePolicy.Always;//直接400
            //});

            //services.AddCors(options =>
            //{
            //    options.AddPolicy("CorsPolicy", policyBuilder => policyBuilder
            //        .AllowAnyOrigin()
            //        .AllowAnyMethod()
            //        .AllowAnyHeader());
            //});
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            //这个要加，不然写不进cooike
            app.UseCookiePolicy();
            //这个要加，不然写不进cooike
            //      app.UseCookiePolicy();
            // app.UseCors("CorsPolicy");
            if (Environment.IsDevelopment())
            {
                app.UseHsts();
                app.UseDeveloperExceptionPage();
            }

            if (!Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.ApplicationServices.GetService<IConsulRegister>()!.ConsulRegistAsync();

            app.UseHealthCheckMiddleware();


            app.UseHttpsRedirection();
            app.UseStaticFiles();

          
            app.UseRouting();
            app.UseIdentityServer();
            app.UseAuthorization();

 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}